package com.iflytek.uoamp.agent.core;

import com.alibaba.fastjson.JSON;
import com.iflytek.uoamp.agent.common.constants.CommonConstants;
import com.iflytek.uoamp.agent.core.agentclient.AgentClient;
import com.iflytek.uoamp.agent.core.agentclient.sync.SyncWrite;
import com.iflytek.uoamp.agent.core.agentinterface.IAgent;
import com.iflytek.uoamp.agent.core.conf.AgentCoreConfig;
import com.iflytek.uoamp.agent.core.sender.obj.MsgType;
import com.iflytek.uoamp.agent.core.sender.obj.RequestData;
import com.iflytek.uoamp.agent.core.sender.obj.ResponseData;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AgentCoreMain
 * @Description: netty客户端初始化以及启动
 * @author qinanyuan
 * @date 2017年3月22日 下午9:08:47
 */
public class AgentCoreMain implements IAgent {
    private static AgentClient agentClient;
    
    private static String LEVEL = "0"; 

    public static AgentClient getAgentClient() {
        return agentClient;
    }

    public static void setClientSocket(AgentClient agentClient) {
        AgentCoreMain.agentClient = agentClient;
    }

    private static String host;

    private static int port;

	    
	@Override
	public void init() {
        try {
            AgentCoreConfig.getInstance().init();
            host = AgentCoreConfig.getInstance().getHost();
            port = AgentCoreConfig.getInstance().getPort();
        } catch (IOException e) {
        	Logger.getRootLogger().error("initCoreData fail! The Exception is ："+ e);
        }
		boolean isLinux = AgentCoreConfig.getInstance().isLinux();
		String log4jPath = "";
		if(isLinux){
			log4jPath = CommonConstants.LINUX_LOG4J_PATH;
		}else {
			log4jPath = CommonConstants.WIN_LOG4J_PATH;
		}
    	DOMConfigurator.configure(log4jPath);
	}

	    
	@Override
	public void start() {
		agentClient = AgentClient.getInstance();
        //开启客户端
		agentClient.start(host ,port);
        //获取clientId
        confirmClientId();
	}

	    
	@Override
	public String getPropertiy() {
		return LEVEL;
	}

    public static void confirmClientId(){
        String clientId = getClientId();
        while(StringUtils.isBlank(clientId)){
            Logger.getRootLogger().info("获取clientId失败，20s后重新获取!");
            try {
                TimeUnit.SECONDS.sleep(CommonConstants.CLIENTID_INTERVAL);
            } catch (InterruptedException e) {
                Logger.getRootLogger().info(e);
            }
            clientId = getClientId();
        }
        Logger.getRootLogger().info("获取clientId成功!" + clientId);
        AgentCoreConfig.getInstance().setClientId(clientId);
    }
    /**
     * @Title: getClientId
     * @Description: 获取clientId
     * @return String
     * @date 2017年7月5日 上午11:26:14
     * @throws
     */
    public static String getClientId() {
        String clientId = null;
        try {
            SyncWrite s = new SyncWrite();
            RequestData request = new RequestData();
            request.setMsgType(MsgType.AUTH);
            request.setRequestInfo("netty Ping test!");
            Logger.getRootLogger().info("注册本机!" + JSON.toJSONString(request));
            Logger.getRootLogger().info("getClientId请求数据：" + JSON.toJSON(request));
            Channel channel = agentClient.getFuture().channel();
            ResponseData response = s.writeAndSync(channel, request,AgentCoreConfig.getInstance().getConnectOutTime());
            Logger.getRootLogger().info("getClientId调用结果：" + JSON.toJSON(response));
            if (StringUtils.isNotBlank(response.getClientId())) {
                clientId = response.getClientId();
            }
        } catch (Exception e) {
            Logger.getRootLogger().error("getClientId fail! The Exception is ：" + e);
        }

        return clientId;
    }
}
